<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/11 0011
 * Time: 10:21
 */

namespace app\index\model;


use think\facade\Config;
use think\facade\Request;
use think\facade\View;
use think\Model;

class Goods extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $updateTime = 'last_update';
    protected $autoWriteTimestamp = true;// 时间戳自动加载
    // 当模型对应的主键不是id时，需要重新指定
    protected $pk = 'goods_id';

    protected $error;//受保护的报错误方法

    public function getError(){
        return $this->error;
    }

    public function searchGoodsNameAttr($query,$value){
        if(isset($value) && '' !== $value){
            $query->whereLike('goods_name','%'.$value.'%');
        }
    }

    public function searchRecommendedAttr($query,$value){
        if (isset($value) && '2'!==$value){
            $query->where('recommended',$value);
        }
    }

    public function searchIfShowAttr($query,$value){
        if (isset($value) && []!==$value){
            $query->whereIn('ecm_goods.if_show',$value);
        }
    }


    public function searchPriceMinAttr($query,$value){
        if(isset($value) && $value !==''){
            $query->where('price','>=',$value);
        }
    }

    public function searchPriceMaxAttr($query,$value){
        if(isset($value) && $value !==''){
            $query->where('price','<=',$value);
        }
    }

    public function searchUpTimeAttr($query,$value){
        if(isset($value) &&!empty($value)){
            $query->whereTime('add_time','>=',$value);
        }
    }

    public function searchDownTimeAttr($query,$value){
        if(isset($value) && !empty($value)){
            $query->whereTime('add_time','<=',$value);
        }
    }

    public function getBrandAttr($value,$data)
    {
        $brand = Brand::field('brand_name')->find($value);
        return $brand['brand_name'];
    }

    public static function getGoodsList($data = [],$query = [],$page = false)
    {

        $field = [
            'goods_id', 'goods_name', 'price', 'g.if_show', 'recommended', 'add_time',
            'c.cate_id', 'c.cate_name', 'default_image','brand','vip','spec_qty','last_update'
        ];

        $model = self::alias('g')
            ->field($field)
            ->join(['ecm_gcategory' => 'c'], 'c.cate_id=g.cate_id and c.if_show=1', 'LEFT')
            //->withSearch($search,$data);
            ->withSearch(array_keys($data), $data);
        $get=Request::get('');
        // 点击排序
        if (isset($get['sort']) && 'desc' == $get['sort']){
            $model=$model->order('add_time','desc');
        }elseif(isset($get['sort']) && 'asc' == $get['sort']){
            $model=$model->order('add_time','asc');
        }else{
            $model=$model->order('goods_id','asc');
        }
//        $list_rows = Config::has('view.list_rows')?Config::get('view.list_rows'):15;

        if ($page) {
            $result = $model->select();
        } else {
            $result = $model->paginate([
                'list_rows' => 10,
                'query' => $query,
            ])->each(function ($item) use ($data) {
                if (isset($data['goods_name']) && '' != $data['goods_name']) {
                    $item['goods_name'] =
                        str_replace($data['goods_name'],
                            '<span style="color: red;font-weight: 900">' . $data['goods_name'] . '</span>', $item['goods_name']);
                    return $item;
                }
            });

            return $result;
        }

    }


    public function goodAdd(array $data, array $allowField = [], bool $replace = false)
    {
        try{
            if(empty($data)){
                $this->error = '新增数据不能为空！';
                return ;
            }
            // 限制写入的字段列表
            if (!empty($allowField))
                $this->allowField($allowField);
            $this->replace($replace)->save($data);

            return true;
        }catch (Exception $ex){
            $this->error = $ex->getMessage();
            return false;
        }
    }
    public function getInsertId(){// 获取id的方法
        $data = $this->toArray();
        return $data[$this->pk];
    }

    public function changegoodlist($data, $where = [], $allowField = [])
    {
        try{
            if (empty($data)){
                $this->error = "修改数据不能为空!!";
                return;
            }
            if (!empty($allowField)){
                $this->allowField($allowField);

            }
            if (!empty($where)){
                $this->setUpdateWhere($where);
                if (isset($data[$this->pk]))  unset($data[$this->pk]);
            }
            return $this->exists(true)->save($data);

        }catch (Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
}